package com.aaa.mbs.service.impl;

import com.aaa.common.constants.BusinessConstant;
import com.aaa.common.util.Result;
import com.aaa.mbs.dao.MemberDao;
import com.aaa.mbs.dao.MemberLevelDao;
import com.aaa.mbs.entity.IntegrationHistory;
import com.aaa.mbs.entity.Member;
import com.aaa.mbs.entity.MemberLevel;
import com.aaa.mbs.entity.MemberVo;
import com.aaa.mbs.service.IntegrationHistoryService;
import com.aaa.mbs.service.MemberLevelService;
import com.aaa.mbs.service.MemberService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.crypto.hash.Sha512Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * (Member)表服务实现类
 *
 * @author yuxiujie
 * @since 2021-01-21 16:09:03
 */
@Service("memberService")
public class MemberServiceImpl implements MemberService {
    @Resource
    private MemberDao memberDao;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private IntegrationHistoryService integrationHistoryService;

    @Autowired
    private MemberLevelService memberLevelService;

    @Autowired
    private MemberLevelDao memberLevelDao;

    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public Member queryById(Integer id) {
        return this.memberDao.queryById(id);
    }

    /**
     * 查询多条数据
     *
     * @param offset 查询起始位置
     * @param limit  查询条数
     * @return 对象列表
     */
    @Override
    public List<Member> queryAllByLimit(int offset, int limit) {
        return this.memberDao.queryAllByLimit(offset, limit);
    }

    /**
     * 新增数据
     * 手机端注册方法
     *
     * @param member 实例对象
     * @return 实例对象
     */
    @Override
    public Member insert(Member member) {
        if (memberDao.count(member) > 0) {
            return null;
        }

        //随机盐值
        String salt = UUID.randomUUID().toString().substring(0, 15);
        //实例化Sha512Hash
        System.out.println(member.getPassword());
        Sha512Hash sha512Hash = new Sha512Hash(member.getPassword(), salt, BusinessConstant.CredentialsPassword.HASH_ITERATIONS);
        member.setStatus(0);
        //保存盐值
        member.setPwSalt(salt);
        //保存密码
        member.setPassword(sha512Hash.toString());
        //调用方法
        memberDao.insert(member);
        //返回值
        return member;
    }

    /**
     * 修改数据
     *
     * @param member 实例对象
     * @return 实例对象
     */
    @Override
    public Member update(Member member) {
        if (memberDao.count(member) > 0) {
            return null;
        }
        this.memberDao.update(member);
        return this.queryById(member.getId());
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Integer id) {
        return this.memberDao.deleteById(id) > 0;
    }

    /**
     * 分页查询多条数据
     *
     * @param member Member
     * @return 对象列表
     */
    @Override
    public PageInfo<Member> queryAll(int pageNo, int pageSize, Member member) {
        PageHelper.startPage(pageNo, pageSize);
        return new PageInfo<>(this.memberDao.queryAll(member));
    }

    @Override
    public Member getMemberByUserName(String userName) {
        Member member = new Member();
        member.setUsername(userName);
        List<Member> members = memberDao.queryAll(member);
        if (!CollectionUtils.isEmpty(members)) {
            return members.get(0);
        }
        return null;
    }

    @Override
    public Result<Integer> queryMemberByPhone(String phoneNum) {
        if (memberDao.queryMemberByPhone(phoneNum) == 0) {
            return new Result<>(2000, "success", 0);
        } else {
            return new Result<>(5000, "error", 1);
        }

    }

    @Override
    public Result<Boolean> insertMember(MemberVo memberVo) {
        String code = redisTemplate.opsForValue().get(memberVo.getPhoneNum());
        if (memberVo.getCode().equals(code)) {
            String salt = UUID.randomUUID().toString().substring(0, 15);
            Sha512Hash sha512Hash = new Sha512Hash(memberVo.getPassword(), salt, BusinessConstant.CredentialsPassword.HASH_ITERATIONS);
            memberVo.setPassword(sha512Hash.toString());
            memberVo.setSalt(salt);
            memberVo.setStatus(0);
            memberVo.setGrowth(0.0);
            int i = memberDao.insertMemberVo(memberVo);
            if (i > 0) {
                return new Result<>(2000, "success", true);
            } else {
                return new Result<Boolean>(5000, "error", false);
            }
        } else {
            return new Result<Boolean>(5000, "error", false);
        }

    }

    @Override
    public Result<Boolean> passwordBack(String phoneNum, String password, String code) {
        String phoneCode = redisTemplate.opsForValue().get(phoneNum);
        if (code.equals(phoneCode)) {
            MemberVo memberVo = new MemberVo();
            String salt = UUID.randomUUID().toString().substring(0, 15);
            Sha512Hash sha512Hash = new Sha512Hash(password, salt, BusinessConstant.CredentialsPassword.HASH_ITERATIONS);
            memberVo.setPhoneNum(phoneNum);
            memberVo.setPassword(sha512Hash.toString());
            memberVo.setSalt(salt);
            if (memberDao.updateMemberVo(memberVo) > 0) {
                return new Result<>(200, "success", true);
            } else {
                return new Result<>(500, "error", false);
            }
        }
        return new Result<>(500, "error", false);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateAccount(Integer memberId, Double amount) {
        Member member = queryById(memberId);
        //修改操作后会员的积分和历史积分.判断每次充值金额，增加相应数量的积分
        if (amount < 5000 && amount >= 0) {
            double v = member.getIntegration() + amount / 10;
            //会员当前积分
            member.setIntegration((int) v);
            //会员历史总积分
            member.setHistoryIntegration(Double.valueOf(member.getHistoryIntegration()) + amount / 10 + "");
        } else if (amount >= 5000 && amount < 10000) {
            double v = member.getIntegration() + amount / 10 * 2;
            member.setIntegration((int) v);
            member.setHistoryIntegration(Double.valueOf(member.getHistoryIntegration()) + amount / 10 * 2 + "");
        } else if (amount >= 10000) {
            double v = member.getIntegration() + amount / 10 * 3;
            member.setIntegration((int) v);
            member.setHistoryIntegration(Double.valueOf(member.getHistoryIntegration()) + amount / 10 * 3 + "");
        }

        //添加历史积分记录表
        IntegrationHistory integrationHistory = new IntegrationHistory();
        integrationHistory.setMemberId(Long.valueOf(memberId));
        integrationHistory.setCreateTime(new Date());
        integrationHistory.setAddtime(new Date());
        integrationHistory.setChangeType(1);
        integrationHistory.setChangeCount(amount.intValue());
        integrationHistory.setOperateMan(member.getName());
        integrationHistory.setOperateNote("充值积分");
        integrationHistory.setSourceType(2);
        integrationHistoryService.insert(integrationHistory);

        //点击充值后修改会员成长值
        //现获取现阶段会员的会员等级和对应的加成
        MemberLevel memberLevel = this.memberLevelService.queryById(Long.valueOf(member.getMemberLevelId()));
        double v = (double) memberLevel.getRatio() * amount;
        member.setGrowth((double) member.getGrowth() + v);

        //判断现在的会员成长值是否达到了会员等级的临界点，如果超过将修改会员的会员等级
        Double growth = (Double) member.getGrowth();
        List<MemberLevel> memberLevels = this.memberLevelDao.queryAll(null);
        MemberLevel memberLevel1 = memberLevels.stream().filter(item -> {
            if (item.getGrowthPoint() < growth) {
                return true;
            } else {
                return false;
            }
        }).max((o1, o2) -> {
            return o1.getGrowthPoint() - o2.getGrowthPoint();
        }).get();

        member.setMemberLevelId(memberLevel1.getId().intValue());

        amount = amount + ((Double) member.getAccountBalance());
        member.setAccountBalance(amount);


        this.memberDao.update(member);

    }

    @Override
    public Result<Boolean> updatePassword(Integer memberId, String oldPassword, String newPassword) {
        Member member = memberDao.queryById(memberId);
        if (member != null) {
            String pwSalt = member.getPwSalt();
            String sha512Hash = new Sha512Hash(oldPassword, pwSalt, BusinessConstant.CredentialsPassword.HASH_ITERATIONS).toString();
            if (member.getPassword().equals(sha512Hash)) {
                String salt = UUID.randomUUID().toString().substring(0, 15);
                Member newMember = new Member();
                newMember.setId(memberId);
                newMember.setPassword(new Sha512Hash(newPassword, salt, BusinessConstant.CredentialsPassword.HASH_ITERATIONS).toString());
                newMember.setPwSalt(salt);
                memberDao.update(newMember);
                return new Result<>(200, "success", true);
            }
        }
        return new Result<>(500, "error", false);
    }

    @Override
    public double updateAccountAndIntegration(int memberId, double totalPrice) {
        //计算积分抵扣钱数
        double v = totalPrice * 0.1;
        double n;
        Member member = this.memberDao.queryById(memberId);
        if (member.getIntegration()>v){
            n=v;
        }else {
            n=member.getIntegration();
        }
        //积分抵扣后剩余的
        member.setIntegration((int) (member.getIntegration()-n));
        //抵扣积分后需要的钱
        double v1 = totalPrice - n;
        //总余额减去本次的消费
        member.setAccountBalance((double)member.getAccountBalance()-v1);
        memberDao.update(member);
        //添加积分使用记录表
        IntegrationHistory integration = new IntegrationHistory();
        integration.setMemberId((long) memberId);
        integration.setCreateTime(new Date());
        integration.setAddtime(new Date());
        integration.setChangeType(2);
        integration.setChangeCount((int) n);
        integration.setOperateMan(member.getName());
        integration.setOperateNote("积分抵扣");
        integration.setSourceType(0);
        integrationHistoryService.insert(integration);
        return n;
    }

}